package com.yonyou.iuap.jxzy.ref.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nc.vo.jcom.lang.StringUtil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.yonyou.iuap.jxzy.ref.service.RefService;
import com.yonyou.iuap.ref.model.RefVertion;
import com.yonyou.iuap.ref.model.RefViewModelVO;

/**
 * 列表参照基类
 * @author WXF
 *
 */
public abstract class AbstractBillRefModel {
	
//	@Autowired
//    private RefCommonService service;
	
	@Autowired
	private RefService refService;
	
	@RequestMapping(value = "/blonRefTree")
    @ResponseBody
	public Map<String, Object> blonRefTree(RefViewModelVO refModel){
//		getRefModelInfo(null, null, refModel);
		Map<String, Object> mapList = new HashMap();
		List<Map<String, Object>>  results = new ArrayList<Map<String,Object>>();
		for(int i = 0 ; i < 3 ;++i){
			 Map<String, Object> mapResult = new HashMap();
			 List<Map<String, Object>> children = new ArrayList<Map<String,Object>>();
			 mapResult.put("refpk", "pk一级"+i);
			 mapResult.put("code", "编码一级"+i);
			 mapResult.put("name", "名称一级"+i);
			 mapResult.put("refname", "名称一级"+i);
			 for(int j = 0 ; j < 5 ; j++){
				 Map<String, Object> map = new HashMap<String, Object>();
				 map.put("refpk", "pk二级"+j);
				 map.put("code", "编码二级"+j);
				 map.put("name", "名称二级"+j);
				 map.put("refname", "名称二级"+j);
				 children.add(map);
			 }
			 mapResult.put("children", children);
			 results.add(mapResult);
		}
		Map<String, Object> page = new HashMap<String, Object>();
		page.put("currPageIndex", 0);
		page.put("pageCount", 2);
		page.put("pageSize", 5);
		page.put("totalElements", 10);
		mapList.put("allpks", null);
		mapList.put("data", results);
		mapList.put("page", page);
		return mapList;
	}
	
	
	@RequestMapping(value = "/blobRefSearch")
    @ResponseBody
	public Map<String, Object> blobRefSearch(RefViewModelVO refModel){
		List<Map<String,Object>> results = getRefData(refModel);
		Map<String, Object> mapList = new HashMap();
		int pageNum = refModel.getRefClientPageInfo().getCurrPageIndex();
		pageNum = pageNum < 0 ? 0 : pageNum;
		int pageSize = refModel.getRefClientPageInfo().getPageSize();
		pageSize = pageSize < 1 ? 10 : pageSize;
		//从第几条数据开始
        int firstIndex = pageNum * pageSize;
        //到第几条数据结束
        int lastIndex = (pageNum+1) * pageSize;
        lastIndex = lastIndex > results.size() ? results.size() : lastIndex;
		Map<String, Object> page = new HashMap();
		page.put("currPageIndex", pageNum);
		page.put("pageCount", Math.ceil(results.size()/(double)pageSize));
		page.put("pageSize", pageSize);
		page.put("totalElements", results.size());
		mapList.put("allpks", null);
		mapList.put("data", results.subList(firstIndex, lastIndex));
		mapList.put("page", page);
		return mapList;
	}
	
	public List<Map<String,Object>> getRefData(RefViewModelVO refModel) {
		PageRequest request = new PageRequest(0, 10, null);
		Page<Map<String, Object>> vopage = this.refService.getTreeRefData(request, getTableName(), 
				getStrFieldCode(),getRefCode(),getRefName(),getRefID(),initWhereSQL(refModel));
		List<Map<String, Object>> retList = toLowerKey(vopage.getContent());
//		this.service.getTreeRefData(request,2, getTableName(), refModel.getContent(),getStrFieldCode(), ids);
		return retList;
	}
	
	public String initWhereSQL(RefViewModelVO refModel){
		String content = refModel.getContent();
		String contentWhere = null;
		if(StringUtils.isNotEmpty(content)){
			contentWhere = getContentSQL(content);
		}
		String wheresql = getWhereSQL(refModel);
		if(contentWhere != null && wheresql != null){
			return wheresql + " and (" + contentWhere +")";
		}else if(contentWhere != null){
			return contentWhere;
		}
		return wheresql;
	}
	
	private String getContentSQL(String content) {
		try {//复杂参照过滤
			Map<String, String> contentJson = JSON.parseObject(content, Map.class) == null ? new HashMap() : (Map)JSON.parseObject(content, Map.class);
			Iterator<String> var14 = contentJson.keySet().iterator();
			StringBuffer sql = new StringBuffer();
			Map<String,String> whereKay = new HashMap<String, String>();
			while(var14.hasNext()) {
				String key = (String)var14.next();
				if (StringUtils.isNotEmpty(contentJson.get(key))) {
					whereKay.put(key, "%"+contentJson.get(key)+"%");
				}
			}
			if(whereKay.size() == 0){
				return null;
			}
			for(String str : whereKay.keySet()){
				sql.append(str + " like '"+whereKay.get(str)+"' and ");
			}
			return sql.toString().substring(0,sql.length()-4);
		} catch (Exception e) {//存在异常判断为简单过滤
			if(!StringUtil.isEmpty(content)){
				StringBuffer sql = new StringBuffer();
				String[] filedcodes = getStrFieldCode();
				for(String filedcode : filedcodes){
					sql.append(filedcode + " like '%"+content+"%'  or ");
				}
				return sql.toString().substring(0,sql.length()-3);
			}
		}
		return "";
	}
	
	/**列表显示编码*/
	public abstract String[] getStrFieldCode();
	/**查询表名*/
	public abstract String getTableName();
	/**类别显示名称*/
	public abstract String[] getStrFieldName();
	/**参照编码*/
	public abstract String getRefCode();
	/**参照名称*/
	public abstract String getRefName();
	/**参照主键*/
	public abstract String getRefID();
	/**过滤条件*/
	public abstract String getWhereSQL(RefViewModelVO refModel);
	

	@RequestMapping(value = "/getRefModelInfo")
    @ResponseBody
	public RefViewModelVO getRefModelInfo(HttpServletRequest request, HttpServletResponse response, RefViewModelVO refViewModel){
		refViewModel.setRefName("测试");
		refViewModel.setRootName("测试");
		refViewModel.setRefVertion(RefVertion.NewRef);
		refViewModel.setRefUIType(null);
		refViewModel.setStrFieldCode(getStrFieldCode());
		refViewModel.setStrFieldName(getStrFieldName());
		refViewModel.setDefaultFieldCount(1);
		return refViewModel;
	}
	
    private List<Map<String, Object>> toLowerKey(List<Map<String, Object>> dataList) {
	      List<Map<String, Object>> dataListResult = new ArrayList();
	      if (dataList != null && dataList.size() > 0) {
	         Iterator var3 = dataList.iterator();

	         while(var3.hasNext()) {
	            Map<String, Object> map = (Map)var3.next();
	            Map<String, Object> mapResult = new HashMap();
	            Iterator var6 = map.entrySet().iterator();

	            while(var6.hasNext()) {
	               Entry<String, Object> entry = (Entry)var6.next();
	               if ("id".equalsIgnoreCase((String)entry.getKey())) {
	                  mapResult.put("refpk", entry.getValue());
	                  mapResult.put(((String)entry.getKey()).toLowerCase(), entry.getValue());
	               } else if ("pid".equalsIgnoreCase((String)entry.getKey())) {
	                  mapResult.put(((String)entry.getKey()).toLowerCase(), entry.getValue() == null ? "" : entry.getValue());
	               } else {
	                  mapResult.put(((String)entry.getKey()).toLowerCase(), entry.getValue());
	               }
	            }

	            dataListResult.add(mapResult);
	         }
	      }

	      return dataListResult;
	   }
	
    /**
     * 通过pk查询所有数据,String pk数组入参
     * @return
     */
//    @RequestMapping(value = {"/getCommonRefData"}, method = {RequestMethod.POST})
//    @ResponseBody
//    public Map<String, Object> commonRefsearch(@RequestBody RefViewModelVO refModel) {
//
//        /*构建表体，其中list中为要查询的字段，必须和表头设置的相同，并且必须为表中的字段值*/
//        RefParamVO refParamVO = RefXMLParse.getInstance().getReParamConfig(refModel.getRefCode());
//        RefParamConfig refParamConfigTable=refParamVO.getRefParamConfigTable();
//        Map<String, Object> mapList = new HashMap<>();
//        List<Map<String, Object>> results = new ArrayList<>();
//        try {
//            /*获取当前页*/
//            int pageNum = refModel.getRefClientPageInfo().getCurrPageIndex();
//            pageNum=pageNum<0?0:pageNum;
//
//            /*每页显示的数量*/
//            int pageSize = refModel.getRefClientPageInfo().getPageSize();
//            pageSize=pageSize<1?10:pageSize;
//
//            /*拼装分页请求对象*/
//            PageRequest request = buildPageRequest(pageNum, pageSize,refParamVO.getRefParamConfigTable());
//
//            String dataPermission=refParamConfigTable.getDataPermission();
//            dataPermission=StringUtils.isEmpty(dataPermission)?refModel.getRefCode():dataPermission;
//            Set<String> ids = DataPermissionCenter.getInstance().getDataPermissionIds(dataPermission, refModel.getClientParam());
//            if ((DataPermissionCenter.getInstance().isUserDataPower(refModel.getClientParam())) && ((ids == null) || (ids.size() < 1))) {
//                mapList.put("dataList", results);
//                mapList.put("refViewModel", refModel);
//                return mapList;
//            }
//            Page<Map<String, Object>> headpage = this.service.getCheckboxData(request,refParamVO.getReftype(), refParamConfigTable, refModel.getContent(), ids);
//
//
//            /*总页数*/
//            refModel.getRefClientPageInfo().setPageCount(headpage.getTotalPages());
//
//            List<Map<String, Object>> headVOs = headpage.getContent();
//
//            if (CollectionUtils.isNotEmpty(headVOs)) {
//                results = buildRtnValsOfCheckboxRef(headVOs);
//            }
//
//            mapList.put("dataList", results);
//            mapList.put("refViewModel", refModel);
//        } catch (Exception e) {
//            System.out.println(e);
//        }
//        return mapList;
//    }

}

